package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //管理员登录
    public Map login(Map map) {
        //1.获取参数
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String verificationCode = map.get("verificationCode").toString();
        String uuid = map.get("uuid").toString();
        //2.比较用户输入的验证码和redis中存储的验证时是否一致
        String redisCode = redisTemplate.opsForValue().get("CODE:" + uuid);
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            throw new BusinessException("验证码失效");
        }
        //如果正确，删除redis中的验证码
        redisTemplate.delete("CODE:" + uuid);
        //3.校验用户名和密码
        //3.1查询数据库中的用户名和密码
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        //3.2对用户传入的密码进行加密
        password = SecureUtil.md5(password);
        //校验
        if (admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        //生成token
        Map tokenMap = new HashMap<>();
        tokenMap.put("id", admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //返回token
        Map retMap = new HashMap();
        retMap.put("token", token);
        return retMap;
    }

    //管理员信息返回
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }
}
